package avicit.im.lantop.basic.archivetemplatemanager.service.impl;

import avicit.im.lantop.basic.archivetemplatemanager.domain.LantopArchiveFileKind;
import avicit.im.lantop.basic.archivetemplatemanager.service.ArchivetemplatemanagerService;
import avicit.platform6.commons.utils.ComUtil;
import avicit.platform6.commons.utils.PojoUtil;
import avicit.platform6.core.domain.BeanBase;
import avicit.platform6.core.exception.DaoException;
import avicit.platform6.core.jdbc.JdbcAvicit;
import avicit.platform6.core.properties.PlatformConstant.OpResult;
import avicit.platform6.core.properties.PlatformConstant.OpType;
import avicit.platform6.core.service.ServiceBase;
import avicit.platform6.modules.system.syslog.service.SysLogUtil;
import org.hibernate.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>金航数码科技有限责任公司</p>
 * <p>作者：钟一华</p>
 * <p>邮箱：feifan1985@163.com</p>
 * <p>创建时间： 2014-9-29 上午10:54:34 </p>
 * <p>类说明：Archivetemplatemanager模块接口实现类</p>
 * <p>修改记录：张坚，2014.11.29； 修改内容：实现方法getNodeName </p>
 */
@Service
public class ArchivetemplatemanagerServiceImpl extends ServiceBase implements ArchivetemplatemanagerService {

    @Resource
    private JdbcAvicit jdbcAvicit;

    /**
     * 更新项目信息
     *
     * @author 赵小龙
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updateProjct(String Id, String projectName) {
        LantopArchiveFileKind fk = new LantopArchiveFileKind();
        Map<String, Object> params = new HashMap<>();
        try {
            // 根据ID更新项目信息
            StringBuffer upToSql = new StringBuffer();
            upToSql.append("UPDATE LANTOP_ARCHIVE_FILE_KIND SET ");
            upToSql.append("ARCHIVE_FILE_KIND_NAME=");
            upToSql.append("'");
            upToSql.append(projectName);
            upToSql.append("'");
            upToSql.append(" WHERE ID=");
            upToSql.append("'");
            upToSql.append(Id);
            upToSql.append("'");
            this.jdbcAvicit.getJdbcTemplate().update(upToSql.toString());
            SysLogUtil.log(fk, null, OpType.update, OpResult.success);
        } catch (Exception e) {
            e.printStackTrace();
            return (Map<String, Object>) params.put("success", "0");
        }
        return (Map<String, Object>) params.put("success", "1");
    }

    /**
     * 新增项目信息
     *
     * @author 赵小龙
     */
    @Override
    public Map<String, Object> saveProject(String orgId, String deptId, String sysId, String projectName, String type, String planNameto, Integer count) {
        LantopArchiveFileKind fk = new LantopArchiveFileKind();
        String name = projectName.replace("'", ""); // 将字符串中包含"'"替换为空
        fk.setId(planNameto);
        Map<String, Object> params = this.savePlan(orgId, deptId, sysId, name, type, fk.getId(), count);  // 添加项目或计划，根据type进行区分    TYPE-[project项目，plan计划]
        SysLogUtil.log(fk, null, OpType.insert, OpResult.success);
        return params;
    }

    /**
     * 删除计划或项目信息
     */
    @Override
    public void deletePlan(String planName) {
        LantopArchiveFileKind fk = new LantopArchiveFileKind();
        fk.setArchiveFileKindName(planName);
        // 查询当前计划下是否有子节点项目
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT ID");
        sbSql.append(" FROM LANTOP_ARCHIVE_FILE_KIND WHERE PARENT_ID=");
        sbSql.append("'");
        sbSql.append(planName);
        sbSql.append("'");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        if (list.size() > 0) {
            for (Map<String, Object> map : list) {
                String parentId = (String) map.get("ID");
                this.deletePlanById(parentId);
                this.deletePlanById(planName);
            }
        } else {
            this.deletePlanById(planName);
        }
        SysLogUtil.log(fk, null, OpType.delete, OpResult.success);
    }

    /**
     * 根据id删除计划信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void deletePlanById(String id) {
        Query q = this.hibernateDao.createQuery("delete LantopArchiveFileKind where id = ?", id);
        int deleteCount = q.executeUpdate();
        logger.debug("删除数:" + deleteCount);
    }

    /**
     * 获取归档模板信息
     */
    @Override
    public List<Map<String, Object>> selectPlan(String commitType, String orgId) {
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT *");
        sbSql.append(" FROM LANTOP_ARCHIVE_FILE_KIND WHERE ARCHIVE_FILE_KIND_CODE=");
        sbSql.append("'");
        sbSql.append(commitType);
        sbSql.append("' AND ORG_ID ='");
        sbSql.append(orgId);
        sbSql.append("'");
        sbSql.append("ORDER BY CREATION_DATE ASC");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        return list;
    }

    /**
     * 新增归档模板计划
     *
     * @author 赵小龙
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> savePlan(String orgId, String depId, String sysId, String name, String type, String parentId, Integer count) {
        Map<String, Object> view = new HashMap<>();
        LantopArchiveFileKind fk = new LantopArchiveFileKind();
        try {
            fk.setId(ComUtil.getId());
            if (type.equals("plan")) {    // type:'plan' 属于计划
                fk.setArchiveFileKindCode("plan");  // 区分标识
                fk.setParentId("ROOT");
            } else if (type.equals("project")) {// type:'project' 属于计划
                fk.setArchiveFileKindCode("project");// 区分标识
                fk.setParentId(parentId);
                fk.setSortNumber(count);
            }
            // 添加其余公共数据
            fk.setArchiveFileKindName(name);
            fk.setNodePath(null);
            fk.setOrgId(orgId);
            fk.setDeptId(depId);
            fk.setSysId(sysId);
            PojoUtil.setSysProperties(fk, OpType.insert);
            this.hibernateDao.save(fk);
            SysLogUtil.log(fk, null, OpType.insert, OpResult.success);
            // 保存成功
            view.put("success", "1");
            return view;
        } catch (Exception e) {
            e.printStackTrace();
            SysLogUtil.log(fk, null, OpType.insert, OpResult.failure);
            // 保存失败
            view.put("success", "0");
            return view;
        }
    }

    /**
     * 查询计划底下所有的项目信息
     */
    @Override
    public List<Map<String, Object>> selectProject(String planName) {
        // 查询当前计划下是否有子节点项目
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT *");
        sbSql.append(" FROM LANTOP_ARCHIVE_FILE_KIND WHERE PARENT_ID=");
        sbSql.append("'");
        sbSql.append(planName);
        sbSql.append("' ");
        sbSql.append("ORDER BY CREATION_DATE ASC,SORT_NUMBER ASC");
        List<Map<String, Object>> list = this.jdbcAvicit.getJdbcTemplate().queryForList(sbSql.toString());
        return list;
    }


    @Override
    public Map<String, Object> selectProjectList(String id, Integer page, Integer rows) {
        Map<String,Object> resultMap = new HashMap<>();
        StringBuffer sbSql = new StringBuffer();
        sbSql.append("SELECT count(1)");
        sbSql.append(" FROM LANTOP_ARCHIVE_FILE_KIND WHERE PARENT_ID=");
        sbSql.append("'");
        sbSql.append(id);
        sbSql.append("' ");
        Long count = this.jdbcAvicit.getJdbcTemplate().queryForObject(sbSql.toString(),Long.class);
        resultMap.put("total",count);
        StringBuffer sbSql1 = new StringBuffer();
        sbSql1.append("SELECT * FROM (SELECT ROW_.*, ROWNUM ROWNUM_ FROM (SELECT ROW_NUMBER() OVER(ORDER BY CREATION_DATE ASC,SORT_NUMBER ASC) SORT,T.* FROM LANTOP_ARCHIVE_FILE_KIND T WHERE T.PARENT_ID='");
        sbSql1.append(id);
        sbSql1.append("'");
        sbSql1.append(" ) ROW_ WHERE ROWNUM <");

        sbSql1.append(page * rows + 1);
        sbSql1.append(" ) WHERE ROWNUM_ >");
        sbSql1.append((page - 1) * rows);
        List<Map<String, Object>> mapList = jdbcAvicit.getJdbcTemplate().queryForList(sbSql1.toString());
        resultMap.put("rows",mapList);
        return resultMap;
    }

    @Override
    public void delete(BeanBase arg0) throws DaoException {
        // TODO Auto-generated method stub

    }

    @Override
    public void insert(BeanBase arg0) throws DaoException {
        // TODO Auto-generated method stub

    }

    @Override
    public void update(BeanBase arg0) throws DaoException {
        // TODO Auto-generated method stub

    }

}
